package com.bootcamp.ex1124.controller;

import com.bootcamp.ex1124.bean.BaseRespVO;
import com.bootcamp.ex1124.bean.User;
import com.bootcamp.ex1124.exception.ParameterException;
import com.bootcamp.ex1124.util.ValidationUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.NoSuchElementException;

/**
 * @program: MyMavenProject
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-24 14:32
 **/

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("login/origin")
    public BaseRespVO login(@Valid User user, HttpSession session) throws ParameterException {
        if (!user.getPassword().matches("[^a-zA-Z]+"))
            throw new ParameterException("passowrd must contains letter!");
        if (user.getUsername().contains("yuanzhi"))
            throw new NoSuchElementException("cannot contains yuanzhi!");
        session.setAttribute("username", user.getUsername());
        return BaseRespVO.ok("登录成功");
    }

    @RequestMapping("login/valid")
    public BaseRespVO loginValid(@Valid User user, BindingResult bind) {
        // 成员变量中有不满足 校验逻辑 则返回true
        if (bind.hasFieldErrors()) {
            // 成员变量，即请求参数 错误
            FieldError fieldError = bind.getFieldError();
            // 获得拒绝值的成员变量名，即请求参数名
            String field = fieldError.getField();
            // 拒绝值
            Object rejectedValue = fieldError.getRejectedValue();
            // 获取默认消息
            String defaultMessage = fieldError.getDefaultMessage();
            // 返回 json数据
            StringBuffer sb =
            new StringBuffer().append("请求参数 ").append(field)
                    .append(" 因为传入 ").append(rejectedValue)
                    .append(" 而失败，失败原因：").append(defaultMessage);
            return BaseRespVO.error(sb.toString());
        }
        return BaseRespVO.ok("登录成功");
    }

    @RequestMapping("login")
    public BaseRespVO loginUtil(@Valid User user, BindingResult bind) throws ParameterException {
        // 成员变量中有不满足 校验逻辑 则返回true
        ValidationUtil.valid(bind);
        return BaseRespVO.ok("登录成功");
    }


}